package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JOptionPane;
import javax.swing.JPanel;

import model.Encryption;
import view.PanelLoggin;

public class LogginController implements ActionListener, FocusListener {
	private PanelLoggin panel;

	public LogginController(JPanel panel) {
		this.panel = (PanelLoggin) panel;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		switch (cmd) {
		case "pass":
			panel.getBtnLoggin().doClick();
			break;
		case "loggin":
			loggin();
			break;
		case "exit":
			if (JOptionPane.showConfirmDialog(panel, "Thoát khỏi hệ thống?",
					"Thoát", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)
				System.exit(0);
			break;
		case "key":
			panel.getPassField().requestFocus();
			break;
		case "config":
//			panel.getBtnConfig().set
			break;
		}
	}

	private void loggin() {
		String tmp = Encryption.encrypt(panel.getUser().concat(
				new String(panel.getPass())));
		try {
			Connection connection = model.Database.connect();

			PreparedStatement preStm = connection
					.prepareStatement("SELECT password from account WHERE name = ?");
			preStm.setString(1, panel.getUser());

			ResultSet rs = preStm.executeQuery();

			while (rs.next()) {
				if (tmp.equals(rs.getString("password"))) {
					panel.notifyShow();
					return;
				}
			}
			
			JOptionPane.showMessageDialog(panel,
					"Tài khoản hoặc mật khẩu không đúng", "Lỗi",
					JOptionPane.ERROR_MESSAGE);
			panel.setText();
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(panel,
					"Lỗi trong khi kết nối cơ sở dữ liệu", "Lỗi",
					JOptionPane.ERROR_MESSAGE);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void focusGained(FocusEvent e) {
		panel.getTxtUser().selectAll();
		panel.getPassField().selectAll();
	}

	@Override
	public void focusLost(FocusEvent e) {

	}

}
